package com.thiny.android.game.thunderbolt.util;

import java.util.HashMap;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;

import com.thiny.android.game.thunderbolt.R;

/**
 * 声音控制播放类，用于播放游戏过程中的音乐
 * 
 * @author THINY
 * 
 */
public class SoundManager {

	private static SoundManager mSoundManager = null;
	// 声音池，android中的类，播放短小的声音时候使用
	private SoundPool mSoundPool;
	private Context mContext;
	// android中的播放音乐类，用于播放背景音乐
	private MediaPlayer mMediaPlayer;
	// 用于存储声音对象的缓冲
	private static final HashMap<Integer, Integer> soundMap = new HashMap<Integer, Integer>();

	public static SoundManager getInstance(Context context) {
		if (mSoundManager == null) {
			mSoundManager = new SoundManager(context);
		}
		return mSoundManager;
	}

	private SoundManager(Context context) {
		mContext = context;
		mMediaPlayer = MediaPlayer.create(mContext, R.raw.bj);
		mMediaPlayer.setLooping(true);
		mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
		soundMap.put(Constants.SOUND_KEY_SHOT,
				mSoundPool.load(context, R.raw.shot, 1));
		soundMap.put(Constants.SOUND_KEY_BULLET_EXPLODE,
				mSoundPool.load(context, R.raw.bullet_explode, 1));
		soundMap.put(Constants.SOUND_KEY_PLAYER_EXPLODE,
				mSoundPool.load(context, R.raw.player_explode, 1));
		soundMap.put(Constants.SOUND_KEY_BOSS_EXPLODE,
				mSoundPool.load(context, R.raw.boss_explode, 1));
		soundMap.put(Constants.SOUND_KEY_GET_PROP,
				mSoundPool.load(context, R.raw.get_prop, 1));

	}

	/**
	 * 开始背景音乐
	 */
	public void startGameMusic() {
		if (!mMediaPlayer.isPlaying() && Utils.isMusicOn(mContext)) {
			mMediaPlayer.start();
		}
	}

	/**
	 * 停止背景音乐
	 */
	public void stopGameMusic() {
		if (mMediaPlayer.isPlaying()) {
			mMediaPlayer.pause();
		}
	}

	/**
	 * 播放小声片段，传入key,进行播放
	 * 
	 * @param key
	 */
	public void playSound(int key) {
		if (Utils.isMusicOn(mContext)) {
			mSoundPool.play(soundMap.get(key), 1, 1, 0, 0, 1);
		}
	}

}
